package com.android.videotest.music.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v4.media.MediaBrowserCompat;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.session.MediaControllerCompat;
import android.support.v4.media.session.PlaybackStateCompat;
import android.text.format.DateUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.Toolbar;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.palette.graphics.Palette;

import com.android.videotest.R;
import com.android.videotest.music.base.BaseMusicActivity;

import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;

public class SimpleMusicActivity extends BaseMusicActivity {
    private static final String TAG = "SimpleMusicActivity-App";
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.seekBar)
    SeekBar seekBar;
    @BindView(R.id.tv_current_time)
    TextView tvCurrentTime;
    @BindView(R.id.tv_end_time)
    TextView tvEndTime;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_play_pause)
    ImageView ivPlayPause;
    @BindView(R.id.iv_previous)
    ImageView ivPrevious;
    @BindView(R.id.iv_next)
    ImageView ivNext;
    @BindView(R.id.iv_album_image)
    ImageView ivAlbumImage;
    @BindView(R.id.contentPanel)
    ConstraintLayout contentPanel;

    public static void start(Context context) {
        Intent starter = new Intent(context, SimpleMusicActivity.class);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        overridePendingTransition(R.anim.anim_bottom_in, R.anim.anim_no);
        setContentView(R.layout.activity_simple_music);
        ButterKnife.bind(this);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setDisplayShowTitleEnabled(false);
        ivNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mMediaBrowserHelper.getTransportControls().skipToNext();
            }
        });
        ivPlayPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mLastPlaybackState != null && mLastPlaybackState.getState() == PlaybackStateCompat.STATE_PLAYING) {
                    mMediaBrowserHelper.getTransportControls().pause();
                } else {
                    mMediaBrowserHelper.getTransportControls().play();
                }
            }
        });
        ivPrevious.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mMediaBrowserHelper.getTransportControls().skipToPrevious();
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:   //返回键的id
                this.finish();
                return false;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        stopSeekbarUpdate();
    }

    @Override
    protected void onConnected(@NonNull MediaControllerCompat mediaController) {
        MediaMetadataCompat metadata = mediaController.getMetadata();
        if (metadata != null) {
            String title = metadata.getString(MediaMetadataCompat.METADATA_KEY_TITLE);
            tvTitle.setText(title);
        }
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                tvCurrentTime.setText(DateUtils.formatElapsedTime(progress / 1000));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                stopSeekbarUpdate();
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mediaController.getTransportControls().seekTo(seekBar.getProgress());
                scheduleSeekbarUpdate();
            }
        });
        scheduleSeekbarUpdate();
    }

    @Override
    protected void onChildrenLoaded(@NonNull String parentId, @NonNull List<MediaBrowserCompat.MediaItem> children) {

    }

    @Override
    protected void onDisconnected() {

    }

    @Override
    protected void onPlaybackStateChanged(PlaybackStateCompat playbackState) {
        mLastPlaybackState = playbackState;
        updatePlaybackStateUI(playbackState);
    }

    @Override
    protected void onMetadataChanged(MediaMetadataCompat mediaMetadata) {
        if (mediaMetadata == null) {
            return;
        }
        updateUI(mediaMetadata);
        updateDuration(mediaMetadata);
        updateProgress();
        scheduleSeekbarUpdate();
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.anim_no, R.anim.anim_bottom_out);
    }

    private void updatePlaybackStateUI(PlaybackStateCompat playbackState) {
        if (playbackState != null) {
            boolean isPlaying = playbackState.getState() == PlaybackStateCompat.STATE_PLAYING;
            if (isPlaying) {
                scheduleSeekbarUpdate();
                ivPlayPause.setImageResource(R.drawable.ic_state_pause);
            } else {
                ivPlayPause.setImageResource(R.drawable.ic_state_play);
            }
        }
    }

    private void updateUI(MediaMetadataCompat metadata) {
        if (metadata != null) {
            CharSequence text = metadata.getText(MediaMetadataCompat.METADATA_KEY_TITLE);
            tvTitle.setText(text);
            Bitmap bitmap = metadata.getBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART);
            ivAlbumImage.setImageBitmap(bitmap);
            if (bitmap == null) {
                return;
            }
            Palette.from(bitmap).generate(palette -> {
                if (palette == null) {
                    return;
                }
//                Palette.Swatch darkMutedSwatch = palette.getDarkMutedSwatch();
//                int mutedColor = palette.getLightMutedColor(0);   //柔和的浅色
//                int mutedColor = palette.getLightVibrantColor(0); //鲜艳的浅色
//                int mutedColor = palette.getDarkMutedColor(0);  //柔和的深色
                int mutedColor = palette.getDarkVibrantColor(0);  //鲜艳深色
//                int mutedColor = palette.getDominantColor(0);  //主要色板的颜色
                contentPanel.setBackgroundColor(mutedColor);
            });
        }
    }

    private static final long PROGRESS_UPDATE_INTERNAL = 1000;
    private static final long PROGRESS_UPDATE_INITIAL_INTERVAL = 100;

    private void updateDuration(MediaMetadataCompat metadata) {
        if (metadata == null) {
            return;
        }

        int duration = (int) metadata.getLong(MediaMetadataCompat.METADATA_KEY_DURATION);
        seekBar.setMax(duration);
        tvEndTime.setText(DateUtils.formatElapsedTime(duration / 1000));
    }

    PlaybackStateCompat mLastPlaybackState;

    private void updateProgress() {
        if (mLastPlaybackState == null) {
            return;
        }
        long currentPosition = mLastPlaybackState.getPosition();
        if (mLastPlaybackState.getState() == PlaybackStateCompat.STATE_PLAYING) {
            // 计算从上一次位置更新到现在为止的时间，除非暂停，否则我们可以假设（delta * speed）+当前位置大约是最新位置。
            // 这确保了我们不会重复调用MediaControllerCompat上的getPlaybackState（）。
            long timeDelta = SystemClock.elapsedRealtime() -
                    mLastPlaybackState.getLastPositionUpdateTime();
            currentPosition += (int) timeDelta * mLastPlaybackState.getPlaybackSpeed();
        }
        seekBar.setProgress((int) currentPosition);
    }

    private final Runnable mUpdateProgressTask = new Runnable() {
        @Override
        public void run() {
            updateProgress();
        }
    };
    private ScheduledFuture<?> mScheduleFuture;
    private final ScheduledExecutorService mExecutorService =
            Executors.newSingleThreadScheduledExecutor();

    private void stopSeekbarUpdate() {
        if (mScheduleFuture != null) {
            mScheduleFuture.cancel(false);
        }
    }

    private final Handler mHandler = new Handler();

    private void scheduleSeekbarUpdate() {
        stopSeekbarUpdate();
        if (!mExecutorService.isShutdown()) {
            mScheduleFuture = mExecutorService.scheduleAtFixedRate(
                    new Runnable() {
                        @Override
                        public void run() {
                            mHandler.post(mUpdateProgressTask);
                        }
                    }, PROGRESS_UPDATE_INITIAL_INTERVAL,
                    PROGRESS_UPDATE_INTERNAL, TimeUnit.MILLISECONDS);
        }
    }

}
